<template>
  <div class="container">
    <h1>Vue3 实现搜索关键字高亮</h1>
    <div class="home">
      <el-input
        input-style="width: 200px"
        v-model="inputValue"
        placeholder="请输入内容"
        @input="searchKey"
      ></el-input>
      <div class="list">
        <div v-for="item in shopList">
          <div class="info">
            <span>{{ item.tag }}</span
            >-
            <span v-if="inputValue" v-html="item.name"></span>
            <span v-else>{{ item.name }}</span
            >-
            <span>{{ item.age }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { createRandomTag } from "../utils/createRandomTag";
const inputValue = ref("");
const searchKey = (val: string) => {
  if (!val) {
    shopList.value = JSON.parse(JSON.stringify(apiData));
    return;
  }

  let reg = new RegExp(val, "gi");
  inputValue.value = val;
  shopList.value = JSON.parse(JSON.stringify(apiData));
  shopList.value = shopList.value.filter((item) => {
    item.name = item.name.replace(reg, (value: any) => {
      console.log(value);
      return `<span style="color: red">${value}</span>`;
    });
    return item.name.indexOf(inputValue.value) > -1;
  });

  console.log(shopList.value);
};
// 模拟接口数据
const apiData = [
  {
    id: 1,
    name: "abc",
    age: 23,
    tag: createRandomTag(23),
  },
  {
    id: 2,
    name: "dfb",
    age: 45,
    tag: createRandomTag(45),
  },
  {
    id: 3,
    name: "cdh",
    age: 34,
    tag: createRandomTag(34),
  },
  {
    id: 4,
    name: "adc",
    age: 34,
    tag: createRandomTag(66),
  },
  {
    id: 5,
    name: "bcg",
    age: 34,
    tag: createRandomTag(17),
  },
  {
    id: 6,
    name: "fgd",
    age: 34,
    tag: createRandomTag(36),
  },
  {
    id: 7,
    name: "cxd",
    age: 34,
    tag: createRandomTag(36),
  },
  {
    id: 8,
    name: "sdf",
    age: 34,
    tag: createRandomTag(36),
  },
];

const shopList = ref(apiData);
</script>
<style scoped lang="scss">
.container {
  width: 400px;
  margin: 100px auto;

  .home {
    border: 1px solid #ccc;
    padding: 50px;
    border-radius: 10px;
    // box-shadow: #ccc 20px 20px 20px;
    .list {
      overflow-y: auto;
      max-height: 240px;
      width: 240px;
      margin-top: 8px;

      .info {
        border: 1px solid #000;
        width: 120px;
        margin: 8px 0;
        border-radius: 5px;
        padding: 3px;
      }
    }
  }
}
</style>
